<?php

namespace App\Spider;

use EasySwoole\RedisPool\RedisPool;

/**
 * Redis操作
 *
 * Class RedisLogic
 * @package App\Spider
 */
class RedisLogic
{
    static $redisName = 'redis';

    static function add($key, $data)
    {
        return RedisPool::invoke(function (\EasySwoole\Redis\Redis $redis) use ($key, $data) {
            if (is_string($data)) {
                $data = [
                    'url' => $data,
                ];
            }
            if (self::checkMap($key, $data['url'])) {
                return true;
            }
            self::addMap($key, $data['url']);

            $result = $redis->rPush($key, json_encode($data, JSON_UNESCAPED_UNICODE));
            return $result;
        }, self::$redisName, 0);
    }

    static function checkMap($key, $url)
    {
        return RedisPool::invoke(function (\EasySwoole\Redis\Redis $redis) use ($key, $url) {
            $key    = $key . 'Map';
            $result = $redis->hGet($key, $url);
            return (bool)$result;
        }, self::$redisName, 0);
    }

    static function addMap($key, $url, $state = 1)
    {
        return RedisPool::invoke(function (\EasySwoole\Redis\Redis $redis) use ($key, $url, $state) {
            $key    = $key . 'Map';
            $result = $redis->hset($key, $url, $state);
            return (bool)$result;
        }, self::$redisName, 0);
    }

    static function clear($key)
    {
        return RedisPool::invoke(function (\EasySwoole\Redis\Redis $redis) use ($key) {
            $result = $redis->del($key);
            return (bool)$result;
        }, self::$redisName, 0);
    }

    static function clearMap($key)
    {
        return RedisPool::invoke(function (\EasySwoole\Redis\Redis $redis) use ($key) {
            $key    = $key . 'Map';
            $result = $redis->del($key);
            return (bool)$result;
        }, self::$redisName, 0);
    }
}